﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Text;

using Gift.DAL;
using Gift.Model;

namespace WebSite.admin.company
{
    public partial class companyList : BaseAdmin
    {

       readonly dalCompany theCompany = new dalCompany();
      public  string ParamentType
        {
            get
            {
                if (string.IsNullOrEmpty(Request.QueryString["type"]))
                {
                    return string.Empty;
                }
                else
                {
                    return Request.QueryString["type"];
                }
            }
        }

      string CompanyParamId
      {
          get
          {
              if (!string.IsNullOrEmpty(Request.QueryString["id"]))
              {
                  return Request.QueryString["id"];
              }
              else
              {
                  if (string.IsNullOrEmpty(base.CompanyId))
                  {
                      return "0";
                  }
                  else
                  {
                      return base.CompanyId;
                  }
              }
          }
      }

      public string HeaderHtml
      {
          get
          {
              if (!string.IsNullOrEmpty(Request.QueryString["id"]) && Request.QueryString["id"] != "0")
              {

                  tbCompany oCompany = theCompany.GetModel(int.Parse(Request.QueryString["id"]));

                  string sHead = string.Format(" <div  class=\"navgater\"><img src=\"../images/module.gif\" width=\"20\" height=\"22\" alt=\"\"/> "
                                            + " 公司名称：{0} "
                                            + " <a style=\" display:block; float:right;\" href=\"javascript:location.href='companyList.aspx?id={1}&type={2}';\" ><img src=\"../images/history.gif\" border=\"0\" /></a>"
                                            + " </div>"
                                            , oCompany.Name
                                            , oCompany.ParentId.ToString()
                                            , ParamentType
                                            );
                  return sHead;
              }
              return string.Empty;

          }


      }
        
        public void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                btnBrachDeleted.OnClientClick = Grid1.GetNoSelectionAlertInTopReference("没有选中项！");
                if (ParamentType == "publish")
                {

                    base.ValidateLoginRule(Gift.Model.ENUM.ERule.AddPublishCompany);
                }
                else if (base.CompanyId == null)
                {
                    base.ValidateLoginRule(Gift.Model.ENUM.ERule.CompanyList);
                }
                this.DeletedCompany();
     
                this.BindProvenctList();
                this.BindCompanyLevel();
                this.BindGrid();
                if (base.AdminTypeId == ((int)Gift.Model.ENUM.EAdminType.Salesman).ToString())
                    {
                        this.Grid1.Columns[10].Hidden = true;
                    }
            }
        }



        private void BindGrid()
        {   // 1.设置总项数
            Grid1.RecordCount = this.theCompany.GetRecordCount(GetSqlWhere);
            string strOrderBy = string.Format("{0} {1} "
                                               , ViewState["sort"] == null ? null : ViewState["sort"].ToString()
                                               , ViewState["dir"] == null ? null : ViewState["dir"].ToString());
            if (strOrderBy.Length < 13)
            {
                strOrderBy = "CompanyCode desc ";
            }
            DataTable table = this.theCompany.GetListByPage(GetSqlWhere, strOrderBy, Grid1.PageIndex, Grid1.PageSize).Tables[0];

            Grid1.DataSource = table;
            Grid1.DataBind();
            Grid1.SelectedRowIndexArray = new int[] { };

        }



        protected void Grid1_PageIndexChange(object sender, ExtAspNet.GridPageEventArgs e)
        {
            Grid1.PageIndex = e.NewPageIndex;
            BindGrid();
        }

        string GetSqlWhere
        {
            get
            {
                StringBuilder strWhere = new StringBuilder();
                strWhere.AppendLine("1=1");
                if (Request.QueryString["type"] == "publish")
                {

                    strWhere.AppendFormat(" and LevelId = 1 ");
                }

                if (this.txtKeywords.Text.Trim() != "")
                {
                    strWhere.AppendFormat(" and (Name like '%{0}%' or CompanyCode = '{0}' or CompanyShortName like '%{0}%')", this.txtKeywords.Text.Trim());
                }
                if (this.ddlLevleResult.SelectedItem.Value != "-1")
                {
                    strWhere.AppendFormat(" and LevelId = {0} ", this.ddlLevleResult.SelectedItem.Value);
                }

                    if(!string.IsNullOrEmpty(base.CompanyId))
                    {
                        strWhere.AppendFormat(" and (id ={0} or parentId={0}) ", base.CompanyId);
                    }
    
                if (this.ddlProvence.SelectedItem.Value != "-1")
                {
                    strWhere.AppendFormat(" and Provence = '{0}'", this.ddlProvence.SelectedItem.Value);
                }
                if (this.ddlCompanyCategory.SelectedItem.Value != "-1")
                {
                    strWhere.AppendFormat(" and companyTypeId = '{0}'", this.ddlCompanyCategory.SelectedItem.Value);
                }
                return strWhere.ToString();
            }
        }

       

        void BindCompanyLevel()
        {
            DataSet ds = theCompany.GetCompanyLevelList();
            if (base.CompanyId != null)
            {
                ds.Tables[0].DefaultView.RowFilter = " Id >= " + base.CompanyLevelId;
            }

            this.ddlLevleResult.DataTextField = "LevelName";
            this.ddlLevleResult.DataValueField = "Id";
            this.ddlLevleResult.DataSource = ds.Tables[0].DefaultView;
            this.ddlLevleResult.DataBind();
            this.ddlLevleResult.Items.Insert(0, new ExtAspNet.ListItem("请选择筛选级别...", "-1"));
            this.ddlLevleResult.SelectedValue = "-1";
        }

        protected void Grid1_Sort(object sender, ExtAspNet.GridSortEventArgs e)
        {
            DataTable table = theCompany.GetListByPage(GetSqlWhere, string.Format("{0} {1}", e.SortField, e.SortDirection), Grid1.PageIndex, Grid1.PageSize).Tables[0];
            Grid1.DataSource = table;
            Grid1.DataBind();
            ViewState["sort"] = e.SortField;
            ViewState["dir"] = e.SortDirection;
        }



        void BindProvenctList()
        {
            string sWhere = "";
              if (!string.IsNullOrEmpty(base.CompanyId))
            {
              sWhere =  string.Format(" and ( id ={0} or parentId={0})",base.CompanyId);
            }

            DataSet ds = theCompany.GetProvenceList(sWhere);
            this.ddlProvence.DataTextField = "provence";
            this.ddlProvence.DataValueField = "provence";


          
            this.ddlProvence.DataSource = ds.Tables[0].DefaultView;
            this.ddlProvence.DataBind();
            this.ddlProvence.Items.Insert(0, new ExtAspNet.ListItem("请选择省份", "-1"));
            this.ddlProvence.SelectedValue = "-1";
        }


        protected void btnBrachDeleted_Click(object sender, EventArgs e)
        {
            int selectedCount = this.Grid1.SelectedRowIndexArray.Length;
            StringBuilder sbProIds = new StringBuilder();
            for (int i = 0; i < selectedCount; i++)
            {
                int rowIndex = this.Grid1.SelectedRowIndexArray[i];
                if (i == selectedCount - 1)
                {
                    sbProIds.Append(this.Grid1.DataKeys[rowIndex][0].ToString());
                }
                else
                {
                    sbProIds.Append(this.Grid1.DataKeys[rowIndex][0].ToString() + ",");
                }
            }
            if (sbProIds.Length > 0)
            {
                theCompany.DeleteMany(sbProIds.ToString());
            }
            ExtAspNet.Alert.Show("批量删除商家成功！");
            this.BindGrid();

           
        }

        protected void btnSearch_Click(object sender, EventArgs e)
        {
            this.BindGrid();
        }

        void DeletedCompany()
        {
            if (Request.QueryString["action"] == "del")
            {
                this.theCompany.Delete(int.Parse(Request.QueryString["id"]));
                ExtAspNet.Alert.Show("删除商家成功！");
            }
        }

        protected void ddlProvence_SelectedIndexChanged(object sender, EventArgs e)
        {
            this.BindGrid();
        }

        protected void ddlLevleResult_SelectedIndexChanged(object sender, EventArgs e)
        {
            this.BindGrid();
        }
    }
}